<template>
  <!-- 上传组件 -->
  <el-upload
    class="single-uploader"
    v-model="imgUrl"
    :show-file-list="false"
    list-type="picture-card"
    :before-upload="beforeUpload"
    :http-request="uploadFile"
  >
    <img v-if="imgUrl" :src="imgUrl" class="single" />
    <el-icon v-else class="single-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { Plus } from "@element-plus/icons-vue";
import {
  ElMessage,
  ElUpload,
  UploadRawFile,
  UploadRequestOptions,
  UploadProps
} from "element-plus";
import axios from "axios";
import feedback from "@/utils/feedback";
import { checkType, uploadApi } from "./util";
import { staticUrl } from "@/utils/file";
const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
  /**
   * 上传类型
   * 0: 图片
   * 1:视频
   * 2:其他
   */
  fileType: {
    type: Number,
    default: 0
  }
});

const imgUrl = computed<string | undefined>({
  get() {
    return props.modelValue;
  },
  set(val) {
    // imgUrl改变时触发修改父组件绑定的v-model的值
    emit("update:modelValue", val);
  }
});
//上传之前校验方法
const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  let checkRes = checkType(props.fileType, rawFile.name);
  if (checkRes) {
    if (rawFile.size / 1024 / 1024 > 10) {
      feedback.msgWarning("只能上传10M以内文件!");
      return false;
    }
    return true;
  } else {
    feedback.msgWarning("不支持的文件类型!");
    return false;
  }
};
/**
 * 自定义图片上传
 *
 * @param options
 */
async function uploadFile(options: UploadRequestOptions): Promise<any> {
  let uploadRes = await uploadApi(options.file);
  if (uploadRes) {
    //上传成功
    imgUrl.value = staticUrl + uploadRes;
  }
}
</script>

<style scoped>
.single-uploader .single {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.single-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.single-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.single-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
